package com.wj.core.net.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

import com.wj.core.common.util.ZkUtil;

import java.util.ArrayList;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

/**
 * @author: wangjun
 * @create: 2018-06-04
 * 服务发现
 **/
public class ZkServiceDiscovery {

  private static final Logger logger = LoggerFactory.getLogger(ZkServiceDiscovery.class);

  private static Executor executor = Executors.newCachedThreadPool();

  static {
    executor.execute(new Runnable() {
      @Override
      public void run() {
        ZkUtil.freshServiceAddress();
        try {
          Thread.sleep(10000);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    });
  }

  public static String discover(String interfaceName) {
    logger.info(" discover :{}", ZkUtil.serviceAddress);
    Set<String> addressSet = ZkUtil.serviceAddress.get(interfaceName);
    if (CollectionUtils.isEmpty(addressSet)) {
      return null;
    }
    String address;
    ArrayList<String> addressStr = new ArrayList<>(addressSet);
    int size = addressStr.size();
    if (size == 1) {
      address = addressStr.get(0);
    } else {
      //随机访问哪台机器
      address = addressStr.get(new Random().nextInt(size));
    }
    return address;
  }
}




